﻿using System.Windows;
using System.Windows.Shapes;

namespace DynamicGeometry
{
    public abstract class LineBase : ShapeBase<Line>, ILinearFigure
    {
        public string c_store_id { get; set; }
        public string c_guid { get; set; }

        public string c_type { get; set; }
        public bool c_is_modify { get; set; }
        protected override Line CreateShape()
        {
            return Factory.CreateLineShape();
        }

        public virtual PointPair OnScreenCoordinates
        {
            get
            {
                return Coordinates;
            }
        }

        public override void UpdateVisual()
        {
            Shape.Set(ToPhysical(OnScreenCoordinates));
        }

        public virtual PointPair Coordinates
        {
            get { return new PointPair(Point(0), Point(1)); }
        }

        public override IFigure HitTest(System.Windows.Point point)
        {
            var basement = Math.GetProjectionPoint(point, Coordinates);
            var distance = point.Distance(basement);
            if (distance < ToLogical(this.Shape.StrokeThickness) + CursorTolerance)
            {
                return this;
            }
            return null;
        }

        public virtual double GetNearestParameterFromPoint(System.Windows.Point point)
        {
            return Math.GetProjectionRatio(Coordinates, point);
        }

        public Point GetPointFromParameter(double parameter)
        {
            PointPair line = Coordinates;
            return new System.Windows.Point(
                line.P1.X + (line.P2.X - line.P1.X) * parameter,
                line.P1.Y + (line.P2.Y - line.P1.Y) * parameter);
        }

        public virtual Tuple<double, double> GetParameterDomain()
        {
            var coordinates = OnScreenCoordinates;
            var p1 = GetNearestParameterFromPoint(coordinates.P1);
            var p2 = GetNearestParameterFromPoint(coordinates.P2);
            return new Tuple<double, double>(p1 * 2, p2 * 2);
        }
    }
}